/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.scene.service.impl;



import com.koron.common.bean.StaffBean;
import com.koron.common.dfs.FastDFSClientWrapper;

import com.koron.common.domain.DataBean;

import com.koron.scene.domain.ProjectTraining;
import com.koron.scene.mapper.ProjectTrainingMapper;
import com.koron.scene.service.api.ProjectTrainingService;
import com.koron.scene.utils.BaseEntityUtil;
import com.koron.scene.utils.BusinessCode;
import com.koron.scene.utils.DateUtil;
import com.koron.scene.utils.ExcelUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.swan.bean.MessageBean;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@Service
public class ProjectTrainingServiceImpl implements ProjectTrainingService {

    private static final Logger logger = LoggerFactory.getLogger(ProjectCertificateServiceImpl.class);

    @Autowired
    private FastDFSClientWrapper clientWrapper;

    @Override
    public MessageBean<?> importExcel(StaffBean user, MultipartFile file, String projectId, String enterpriseId) {
        MessageBean<?> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), Object.class);
        if (StringUtils.isBlank(projectId) || StringUtils.isBlank(enterpriseId)) {
            msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
            msg.setDescription(BusinessCode.INSUFFICIENT_PARAM.getDescription());
            return msg;
        }
        String filePath = null;
        SessionFactory factory = new SessionFactory();
        try {
            ProjectTrainingMapper mapper = factory.getMapper(ProjectTrainingMapper.class);
            //先将文件上传到文件服务器
            if (null == file) {
                msg.setCode(22001);
                msg.setDescription("上传文件为空");
                return msg;
            }
            String fileName = file.getOriginalFilename();
            filePath = clientWrapper.uploadFile(file) + "#" + fileName;//文件上传的路径
            //处理excel中的内容
            InputStream inputStream = file.getInputStream();
            XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
            if (null == workbook) {
                logger.error("上传文件为空");
                msg.setCode(22001);
                msg.setDescription("上传文件为空");
                return msg;
            }
            XSSFSheet sheet = workbook.getSheetAt(0);
            if (sheet == null) {
                logger.error("上传文件为空");
                msg.setCode(22001);
                msg.setDescription("上传文件为空");
                return msg;
            }
            List<ProjectTraining> projectTrainingList = new ArrayList<>();
            int rowsNum = sheet.getPhysicalNumberOfRows();
            for (int i = 1; i < rowsNum; i++) {
                XSSFRow row = sheet.getRow(i);
                ProjectTraining projectTraining = parseRow(row, user, projectId, enterpriseId);
                if (projectTraining != null) {
                    projectTrainingList.add(projectTraining);
                }
            }
            if (projectTrainingList != null && projectTrainingList.size() > 0) {
//                List<ProjectTraining> insertList = new ArrayList<>();
//                //新导入的去重
//                List<ProjectTraining> newDistinctList = new ArrayList<>();
//                for (ProjectTraining p : projectTrainingList) {
//                    boolean result = newDistinctList.stream().anyMatch(np -> p.getIdCardNumber().equals(np.getIdCardNumber()) && p.getCertificateName().equals(np.getCertificateName()));
//                    if (!result) {
//                        newDistinctList.add(p);
//                    }
//                }
//                //获取已经保存的证照
//                List<ProjectTraining> exitList = mapper.queryList(null, null, projectId, enterpriseId, null, null);
//                if (exitList != null && exitList.size() > 0) {
//                    List<ProjectTraining> sameList = new ArrayList<>();
//                    for (ProjectTraining p : exitList) {
//                        for (ProjectTraining sp : newDistinctList) {
//                            if (p.getIdCardNumber().equals(sp.getIdCardNumber()) && p.getTrainName().equals(sp.getTrainName())) {
//                                sameList.add(sp);
//                                //更新已存在的
//                                ProjectTraining up = new ProjectTraining();
//                                up.setStaffName(sp.getStaffName());
//                                up.setExamTime(sp.getExamTime());
//                                up.setTrainTime(sp.getTrainTime());
//                                up.setPassFlag(sp.getPassFlag());
//                                up.setId(p.getId());
//                                BaseEntityUtil.setUpdateBaseProperties(up, user);
//                                mapper.updateByPrimaryKeySelective(up);
//                            }
//                        }
//                    }
//                    if (sameList != null && sameList.size() > 0) {
//                        insertList = newDistinctList.stream().filter(np -> !sameList.stream().anyMatch(sp -> np.getIdCardNumber().equals(sp.getIdCardNumber()) && np.getCertificateName().equals(sp.getCertificateName()))).collect(Collectors.toList());
//                    }
//                } else {
//                    insertList = newDistinctList;
//                }

                if (projectTrainingList != null && projectTrainingList.size() > 0) {
                    mapper.insertList(projectTrainingList);
                }
            }
        } catch (
                Exception e) {
            logger.error(e.getMessage(),e);
            if (!StringUtils.isEmpty(filePath)) {
                clientWrapper.deleteFile(filePath.split("#")[0]);
            }
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            factory.close(false);
        } finally {
            if (factory != null) {
                factory.close();
            }
        }
        return msg;
    }

    @Override
    public MessageBean<?> list(StaffBean user, String staffName, String trainName, String projectId, String enterpriseId, Integer page, Integer pageSize) {
        MessageBean<DataBean> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), DataBean.class);
        try (SessionFactory factory = new SessionFactory()) {
            ProjectTrainingMapper mapper = factory.getMapper(ProjectTrainingMapper.class);
            Integer start = null;
            if (page != null && pageSize != null && page > 0 && pageSize > 0) {
                start = (page - 1) * pageSize;
            }
            List<ProjectTraining> projectTrainingList = mapper.queryList(staffName, trainName, projectId, enterpriseId, start, pageSize);
            int total = mapper.queryListTotal(staffName, trainName, projectId, enterpriseId);
            DataBean dataBean = new DataBean();
            dataBean.setList(projectTrainingList);
            dataBean.setTotalNumber(total);
            dataBean.setPageNo(page);
            dataBean.setPageSize(pageSize);
            dataBean.setTotalPage(start == null ? null : total % pageSize == 0 ? total / pageSize : (total / pageSize + 1));
            msg.setData(dataBean);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
        }
        return msg;
    }

    @Override
    public MessageBean<?> saveUpdate(StaffBean user, List<ProjectTraining> projectTrainingList) {
        MessageBean<?> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), Object.class);
        SessionFactory factory = new SessionFactory();
        try {
            ProjectTrainingMapper mapper = factory.getMapper(ProjectTrainingMapper.class);
            msg = checkProjectTraining(projectTrainingList);
            if (msg.getCode() != 0) {
                return msg;
            }
            for (ProjectTraining projectTraining : projectTrainingList) {
                if (StringUtils.isNotBlank(projectTraining.getId())) {
                    //修改
                    BaseEntityUtil.setUpdateBaseProperties(projectTraining, user);
                    mapper.updateByPrimaryKeySelective(projectTraining);
                } else {
                    //新增
                    BaseEntityUtil.setAddBaseProperties(projectTraining, user);
                    mapper.insert(projectTraining);
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            factory.close(false);
        } finally {
            if (factory != null) {
                factory.close();
            }
        }
        return msg;
    }

    @Override
    public MessageBean<?> delete(String projectTrainingId) {
        MessageBean<?> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), Object.class);
        SessionFactory factory = new SessionFactory();
        try {
            if (StringUtils.isBlank(projectTrainingId)) {
                msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
                msg.setDescription(BusinessCode.INSUFFICIENT_PARAM.getDescription());
                return msg;
            }
            ProjectTrainingMapper mapper = factory.getMapper(ProjectTrainingMapper.class);
            mapper.deleteByPrimaryKey(projectTrainingId);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            factory.close(false);
            return msg;
        } finally {
            if (factory != null) {
                factory.close();
            }
        }
        return msg;
    }

    @Override
    public MessageBean<?> exportList(StaffBean user, String staffName, String trainName, String projectId, String enterpriseId) {
        MessageBean<List> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), List.class);
        try (SessionFactory factory = new SessionFactory()) {
            ProjectTrainingMapper mapper = factory.getMapper(ProjectTrainingMapper.class);
            List<ProjectTraining> projectTrainingList = mapper.queryList(staffName, trainName, projectId, enterpriseId, null, null);
            msg.setData(projectTrainingList);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
        }
        return msg;
    }

    //对象校验
    MessageBean<?> checkProjectTraining(List<ProjectTraining> list) {
        MessageBean<?> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), BusinessCode.SUCCESS.getDescription(), Object.class);
        if (list == null || list.isEmpty()) {
            msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
            msg.setDescription(BusinessCode.INSUFFICIENT_PARAM.getDescription());
            return msg;
        }
        for (ProjectTraining training : list) {
            if (training == null) {
                msg.setCode(BusinessCode.TRAINING_CANNOT_EMPTY.getCode());
                msg.setDescription(BusinessCode.TRAINING_CANNOT_EMPTY.getDescription());
                return msg;
            }
            if (StringUtils.isBlank(training.getProjectId()) || StringUtils.isBlank(training.getEnterpriseId())) {
                msg.setCode(BusinessCode.TRAINING_CANNOT_EMPTY.getCode());
                msg.setDescription(BusinessCode.TRAINING_CANNOT_EMPTY.getDescription());
                return msg;
            }
            if (StringUtils.isBlank(training.getStaffName())) {
                msg.setCode(BusinessCode.TRAINING_STAFF_NAME_CANNOT_EMPTY.getCode());
                msg.setDescription(BusinessCode.TRAINING_STAFF_NAME_CANNOT_EMPTY.getDescription());
                return msg;
            }
            if (StringUtils.isBlank(training.getIdCardNumber())) {
                msg.setCode(BusinessCode.TRAINING_ID_CARD_CANNOT_EMPTY.getCode());
                msg.setDescription(BusinessCode.TRAINING_ID_CARD_CANNOT_EMPTY.getDescription());
                return msg;
            }
            if (StringUtils.isBlank(training.getTrainName())) {
                msg.setCode(BusinessCode.TRAINING_NAME_CANNOT_EMPTY.getCode());
                msg.setDescription(BusinessCode.TRAINING_NAME_CANNOT_EMPTY.getDescription());
                return msg;
            }
            if (training.getTrainTime() == null) {
                msg.setCode(BusinessCode.TRAINING_TIME_CANNOT_EMPTY.getCode());
                msg.setDescription(BusinessCode.TRAINING_TIME_CANNOT_EMPTY.getDescription());
                return msg;
            }
        }
        return msg;
    }

    ;

    //行转换
    private ProjectTraining parseRow(XSSFRow row, StaffBean user, String projectId, String enterpriseId)
            throws Exception {
        ProjectTraining projectTraining = new ProjectTraining();
        projectTraining.setProjectId(projectId);
        projectTraining.setEnterpriseId(enterpriseId);

//        培训课程
        String trainName = ExcelUtil.getCellValue(row.getCell(0));
//        人员
        String staffName = ExcelUtil.getCellValue(row.getCell(1));
//        身份证
        String idCardNumber = ExcelUtil.getCellValue(row.getCell(2));

//       培训时间
        String trainTimeStr = ExcelUtil.getCellValue(row.getCell(3));
//        考试时间
        String examTimeStr = ExcelUtil.getCellValue(row.getCell(4));
//        是否通过
        String passFlag = ExcelUtil.getCellValue(row.getCell(5));

        if (StringUtils.isBlank(trainName)) {
            return null;
        } else {
            projectTraining.setTrainName(trainName);
        }
        if (StringUtils.isBlank(staffName)) {
            return null;
        } else {
            projectTraining.setStaffName(staffName);
        }
        if (StringUtils.isBlank(idCardNumber)) {
            return null;
        } else {
            projectTraining.setIdCardNumber(idCardNumber);
        }

        if ("是".equals(passFlag)) {
            projectTraining.setPassFlag(1);
        } else {
            projectTraining.setPassFlag(0);
        }
        Date trainTime = DateUtil.formatStringToDate(trainTimeStr, DateUtil.DATE_FORMAT_YMD);
        if (trainTime != null) {
            projectTraining.setTrainTime(trainTime);
        }
        Date examTime = DateUtil.formatStringToDate(examTimeStr, DateUtil.DATE_FORMAT_YMD);
        if (trainTime != null) {
            projectTraining.setExamTime(examTime);
        }
        BaseEntityUtil.setAddBaseProperties(projectTraining, user);
        return projectTraining;
    }
}
